<template>
  <el-cascader v-model="modelValue" :options="optionsList" clearable v-bind="defaultAttr" style="width: 100%">
  </el-cascader>
</template>

<script setup>
// v-model值
const modelValue = defineModel()

// 输入框配置项
const props = defineProps({
  // 配置项
  config: {
    type: Object,
    default: () => {},
  },
  // 表单的值
  form: {
    type: Object,
    default: () => {},
  },
})
const defaultAttr = computed(() => {
  // 设置默认绑定值
  const { config } = props
  let { attrs = {} } = config
  // 获取默认项
  attrs['placeholder'] = attrs?.placeholder || `请选择${config.label}`
  return { ...attrs }
})

// options项
const optionsList = ref([])
// 解析
const parseOptions = (value) => {
  const { config } = props
  // 返回数组
  if (Array.isArray(config.options)) {
    initOptions(config.options)
    // 返回方法
  } else if (typeof config.options === 'function') {
    const result = config.options(value)
    if (result.then) {
      result
        .then((list) => {
          initOptions(list)
        })
        .catch((err) => {
          initOptions([])
        })
    } else if (Array.isArray(result)) {
      initOptions(result)
    }
  }
}
// 赋值
const initOptions = (options) => {
  optionsList.value = options
}

onMounted(() => {
  parseOptions(props.form)
})
// 监听options
watch(
  () => props.form,
  () => {
    if (props.config.linkage) {
      parseOptions(props.form)
    }
  },
  { deep: true }
)
</script>

<style lang="scss" scoped></style>
